//
//  PicShowViewController.m
//  HuateVideo
//
//  Created by  on 12-6-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PicShowViewController.h"
#import "CommonWebServices.h"
#import "DataList.h"
#import "Cache.h"
#import "CacheManager.h"
#import "Movie.h"
@interface PicShowViewController ()

@end

@implementation PicShowViewController
@synthesize imgCount;
@synthesize picListArray;
- (void)dealloc{
	[picListArray release];
	[downloaderArray release];
	[super dealloc];
}
-(void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
    
    [(CustomTabBarController*)self.tabBarController ShowTabBarWithAnimate];
    
	if (downloaderArray.count) {
        [downloaderArray makeObjectsPerformSelector:@selector(cancelDownload)];
    }	
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
		downloaderArray=[[NSMutableArray alloc] init];
    }
    return self;
}
- (void)loadIMGData{

	[self initScrollBG:picListArray];

	//CommonWebServices *webServ = [[CommonWebServices alloc] init];
//    webServ.delegate = self;
//	NSMutableDictionary *parma = [NSMutableDictionary dictionary];
//    [parma setValue:imgCount forKey:@"id"];
//    [webServ startRequestWithMode:@"Default" Action:@"GetDetailPicture" Parma:parma Class:@"DataList" RootXML:@"GetDetailPictureResult" resultIsArray:YES];
//    [webServ release];
	
}
#pragma mark - CommonWebServicesDelegate

- (void)onCommonWebServicesWithCustomClass:(id)object {
    if (object) {
        NSArray *movieList = ((DataList *)object).List;
//        if (movieList.count) {
//            [array removeAllObjects];
//        }
//        if ([movieList count]>0) {
//            [array addObjectsFromArray:movieList];
//            [table reloadData];
//            [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
//        }
		[self initScrollBG:movieList];
    }
    
    [self.view showProgressText:NO];
}

- (void)onCommonWebServicesFaild
{
    [self.view showProgressText:NO];
    
    UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"加载失败")  
                                                        message:LS(@"请检查网络连接和设置")
                                                       delegate:self 	
                                              cancelButtonTitle:LS(@"确定")
                                              otherButtonTitles:nil];		
    [alertview show];		
    [alertview release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=LS(@"图片");
    UIBarButtonItem* rightb=[[UIBarButtonItem alloc] initWithTitle:LS(@"收藏") style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    self.navigationItem.rightBarButtonItem=rightb;
    [rightb release];
	// Do any additional setup after loading the view.
	[self addToRecord];
    [self loadIMGData];
}

- (void)share{
    NSMutableArray *tmpArray = (NSMutableArray *)[UserDefaults objectForKey:COLLECTION_VIDEOS_STORE_KEY];
    
    if (!tmpArray) {
        tmpArray = [NSMutableArray array];
    }
    
    BOOL has = NO;
    for (int i=0; i<[tmpArray count]; i++) {
        id hasMovie = [tmpArray objectAtIndex:i];
        
        if ([[hasMovie News_id] isEqualToString:[[picListArray objectAtIndex:imgCount] News_id]]) {
            has = YES;
            break;
        }
    }
    
    if (!has) {
        id movie=[picListArray objectAtIndex:imgCount];
        [movie setDetailType:MovieChannelTypePic];
        [tmpArray insertObject:movie atIndex:0];
        
        if (tmpArray) {
            [UserDefaults setObject:tmpArray forKey:COLLECTION_VIDEOS_STORE_KEY];
        }
        
        UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                            message:LS(@"成功添加到收藏夹")
                                                           delegate:self 								  
                                                  cancelButtonTitle:LS(@"确定")
                                                  otherButtonTitles:nil];		
        [alertview show];		
        [alertview release];
    }
    else {
        UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"提示")  
                                                            message:LS(@"已存在于收藏列表中")
                                                           delegate:self 								  
                                                  cancelButtonTitle:LS(@"确定")
                                                  otherButtonTitles:nil];		
        [alertview show];		
        [alertview release];
    }
}

-(void)addToRecord{
	NSMutableArray* records=[UserDefaults objectForKey:PlAYRECORDING_KEY];
	if (records==nil) {
		records=[NSMutableArray array];
	}
	for (int i=0;i<records.count;i++) {
        id mov=[records objectAtIndex:i];
		if ([[mov News_id] isEqualToString:[[picListArray objectAtIndex:imgCount] News_id]]) {
			[records removeObject:mov];
			break;
		}
	}
    id movie=[picListArray objectAtIndex:imgCount];
        [movie setDetailType:MovieChannelTypePic];
	[records insertObject:movie atIndex:0];
	[UserDefaults setObject:records forKey:PlAYRECORDING_KEY];	
	[[NSNotificationCenter defaultCenter] postNotificationName:REFRESHRECORD object:nil];
}
- (void)initScrollBG:(NSArray*)imgArray{		
	int count=imgArray.count;
    scroll=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    scroll.contentSize=CGSizeMake(320*count, 460);
	scroll.contentOffset=CGPointMake(320*imgCount, 0);
    scroll.pagingEnabled=YES;
    scroll.clipsToBounds=YES;
    scroll.bounces=NO;
    for (int i=0; i<count; i++) {
		id movie=[imgArray objectAtIndex:i];
		
        UIImageView* imgview=[[UIImageView alloc] initWithFrame:CGRectMake(i*320+10,10, 300, 480-44-40)];
		imgview.tag=i+1000;
		
		NSString* picUrl=[movie News_pic];
		if ([picUrl isEqual:[NSNull null]]||(![picUrl isKindOfClass:[NSString class]])) {
			imgview.image=[UIImage imageNamed:@"dengdai.png"];
			return;
		}
		
		Cache* cache=[CacheManager queryCacheWithCacheKey:picUrl];
		if ([cache csize]) {
			NSData *data = [NSData dataWithContentsOfFile: cache.cobject];
			imgview.image = [UIImage imageWithData: data];
		}else {
			//NSLog(@"====%d======%@",i,picUrl);
			imgview.image=[UIImage imageNamed:@"dengdai.png"];
			ImageDownloader* downloader=[[ImageDownloader alloc] init];
			downloader.delegate=self;
			downloader.tag=i+1000;
			downloader.imageURL=picUrl;
			[downloader startDownload:YES];
			[downloader release];
			[imgview showProgressText:YES];
			[downloaderArray addObject:downloader];
		}

		
		
        [scroll addSubview:imgview];
        [imgview release];
    }
    [self.view addSubview:scroll];
    [self.view bringSubviewToFront:scroll];
    [scroll release];
    //NSLog(@"%@",self.view.subviews);

    [(CustomTabBarController*)self.tabBarController dissmissTabBarWithAnimate];
}

-(void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
	//NSLog(@"%d",tag);
	UIImageView* imageview=(UIImageView*)[scroll viewWithTag:tag];
	imageview.image=image;
	[imageview showProgressText:NO];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
